﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using XingFuStudio.Pioneer.Net;
using XingFuStudio.Pioneer.Entity;
using XingFuStudio.Pioneer.IO;
using XingFuStudio.Pioneer.Data;
using XingFuStudio.Pioneer.Container.Interface.Event;

namespace XingFuStudio.Pioneer.BusinessLogic {
    /// <summary>
    /// 开心网好友管理业务逻辑类
    /// </summary>
    public class FriendManager {

        #region 事件

        /// <summary>
        /// 打印日志事件
        /// </summary>
        public event EventHandler<LogEventArgs> PringLog = null;

        /// <summary>
        /// 执行打印日志事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="isNewLine"></param>
        /// <param name="format"></param>
        /// <param name="args"></param>
        private void DoPringLog(object sender, bool isNewLine, string format, params object[] args) {
            if (this.PringLog != null) {
                this.PringLog(sender, new LogEventArgs() {
                    IsNewLing = isNewLine, LogMessage = String.Format(format, args)
                });
            }
        }

        #endregion

        /// <summary>
        /// 声明开心网Http请求处理类对象
        /// </summary>
        private HttpManager httpManager = null;
        /// <summary>
        /// 好友数据访问对象
        /// </summary>
        private DbFriend dbFriend = null;

        /// <summary>
        /// 创建一个<see cref="FriendManager"/>实例
        /// </summary>
        private FriendManager() {
        
        }

        /// <summary>
        /// 创建一个<see cref="FriendManager"/>实例
        /// </summary>
        /// <param name="httpManager">一个<see cref="HttpManager"/>对象</param>
        public FriendManager(HttpManager httpManager) {
            //初始化开心网Http请求处理类对象
            this.httpManager = httpManager;
            //初始化好友数据访问对象
            this.dbFriend = new DbFriend();
        }

        /// <summary>
        /// 获取全部朋友信息
        /// </summary>
        /// <param name="account">帐户信息</param>
        /// <returns>朋友列表</returns>
        public List<FriendInfo> GetFriends(AccountInfo account) {
            //获取全部好友对象
            List<FriendInfo> friends = this.dbFriend.GetFriends();

            //声明朋友集合
            List<FriendInfo> list = new List<FriendInfo>();

            //声明好友起始索引
            int startIndex = 0;
            //声明页大小
            int pageSize = 20;

            //赋值朋友列表的Url
            string url = String.Format("http://www.kaixin001.com/friend/index.php?uid={0}&viewtype=&start={1}",
                account.UserId, startIndex);
            //通过Get方式调用Url, 获取朋友页面的信息
            string content = httpManager.Get(url);

            //获取好友总数
            int friendCount = content.GetMidInteger("共有", "位好友");
            //获取朋友的分页数
            int pageNumber = (friendCount % pageSize) == 0 ? friendCount / pageSize : friendCount / pageSize + 1;

            //计数器
            int count = 0;

            //循环页码
            for (int i = 0; i < pageNumber; i++) {
                //声明位置索引
                int pos = -1;
                //获取好友ID
                string friendId = content.GetMidString("javascript:editFriend('", "'", out pos);

                //循环, 判断朋友ID是否为空
                while (!String.IsNullOrEmpty(friendId)) {
                    //打印日志
                    this.DoPringLog(this, true, "正在更新第{0}/{1}位好友...", ++count, friendCount);

                    //声明好友对象
                    FriendInfo friend = new FriendInfo();
                    if (friends.Count(s => s.UserId == friendId) > 0) {
                        friend = friends.First(s => s.UserId == friendId);
                    } else {
                        //获取好友对象
                        friend = this.GetFriend(friendId);
                        //存储好友
                        this.dbFriend.CreateFriend(friend);
                    }
                    //添加好友对象到集合
                    list.Add(friend);

                    //获取后面的字符串
                    content = content.Substring(pos);
                    //获取朋友ID
                    friendId = content.GetMidString("javascript:editFriend('", "'", out pos);
                }

                //判断下一页是否还在有效页码内
                if ((i + 1) < pageNumber) {
                    //重新计算起始好友索引
                    startIndex = (i + 1) * pageSize;

                    //赋值下一页的Url
                    url = String.Format("http://www.kaixin001.com/friend/index.php?uid={0}&viewtype=&start={1}",
                        account.UserId, startIndex);
                    //通过Get方式调用Url, 获取朋友页面的信息
                    content = httpManager.Get(url);
                }
            }

            //返回朋友集合
            return list;
        }

        /// <summary>
        /// 获取朋友信息
        /// </summary>
        /// <param name="httpManager"></param>
        /// <param name="friendId">朋友ID</param>
        /// <returns>朋友对象<see cref="FriendInfo"/></returns>
        private FriendInfo GetFriend(string friendId) {
            //声明朋友对象
            FriendInfo friend = new FriendInfo();

            //赋值种子列表的Url
            string url = String.Format("http://www.kaixin001.com/home/?uid={0}", friendId);

            //通过Get方式调用Url, 获取种子页面的信息
            string content = httpManager.Get(url);

            friend.UserId = friendId;
            friend.UserName = content.GetMidString("<title>", "的首页");
            friend.Gender = content.GetMidString("性别：</td><td>&nbsp;</td><td><span class=\"sl\" style=\"display:inline-block;width:300px;\">", "</span>") == "男" ? 
                Gender.Male : Gender.FeMale;

            //返回朋友对象
            return friend;
        }
    }
}
